package com.firebird.quartz.server.impl;

import java.text.ParseException;

import javax.annotation.Resource;

import com.firebird.core.auth.domain.LoginUser;
import com.firebird.core.time.TimeTool;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.firebird.quartz.dao.FirebirdQzSchedulerDaoInter;
import com.firebird.quartz.dao.FirebirdQzTaskDaoInter;
import com.firebird.quartz.dao.FirebirdQzTriggerDaoInter;
import com.firebird.quartz.domain.FirebirdQzScheduler;
import com.firebird.quartz.domain.FirebirdQzTask;
import com.firebird.quartz.domain.FirebirdQzTrigger;
import com.firebird.quartz.server.FirebirdQzSchedulerManagerInter;
import com.firebird.core.sql.query.DataQuery;

/**
 * 计划任务管理
 * 
 * @author MAC_wd
 */
@Service
public class FirebirdQzSchedulerManagerImpl implements FirebirdQzSchedulerManagerInter {
	@Resource
	private FirebirdQzSchedulerDaoInter firebirdQzSchedulerDao;
	@Resource
	private FirebirdQzTaskDaoInter firebirdQzTaskDao;
	@Resource
	private FirebirdQzTriggerDaoInter firebirdQzTriggerDao;

	private static final Logger log = Logger
			.getLogger(FirebirdQzSchedulerManagerImpl.class);

	private static Scheduler scheduler = null;

	@Override
	@Transactional
	public void start() throws SchedulerException, ParseException,
			ClassNotFoundException {
		if (scheduler == null) {
			scheduler = StdSchedulerFactory.getDefaultScheduler();
		}
		scheduler.start();
		for (FirebirdQzScheduler node : firebirdQzSchedulerDao.getAutoSchedulers()) {
			FirebirdQzTask task = getTaskEntity(node.getTaskid());
			FirebirdQzTrigger trigger = getTriggerEntity(node.getTriggerid());
			JobDetail job = new QuartzImpl().getJobDetail(node, task);
			Trigger qtrigger = new QuartzImpl().getTrigger(node, trigger);
			scheduler.scheduleJob(job, qtrigger);
		}
	}

	@Override
	@Transactional
	public boolean isRunningFindScheduler(String SchedulerId)
			throws SchedulerException {
		FirebirdQzScheduler node = getSchedulerEntity(SchedulerId);
		FirebirdQzTask task = getTaskEntity(node.getTaskid());
		if (scheduler.getJobDetail(new QuartzImpl().getJobKey(node, task)) == null) {
			return false;
		} else {
			return true;
		}
	}

	@Override
	@Transactional
	public void startTask(String SchedulerId) throws ClassNotFoundException,
			ParseException, SchedulerException {
		FirebirdQzScheduler node = getSchedulerEntity(SchedulerId);
		FirebirdQzTask task = getTaskEntity(node.getTaskid());
		FirebirdQzTrigger trigger = getTriggerEntity(node.getTriggerid());
		JobDetail job = new QuartzImpl().getJobDetail(node, task);
		Trigger qtrigger = new QuartzImpl().getTrigger(node, trigger);
		scheduler.scheduleJob(job, qtrigger);
	}

	@Override
	@Transactional
	public void stopTask(String SchedulerId) throws SchedulerException {
		FirebirdQzScheduler node = getSchedulerEntity(SchedulerId);
		FirebirdQzTask task = getTaskEntity(node.getTaskid());
		scheduler.deleteJob(new QuartzImpl().getJobKey(node, task));
	}

	@Override
	@Transactional
	public FirebirdQzScheduler insertSchedulerEntity(FirebirdQzScheduler entity,
			LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setCusername(user.getName());
		entity.setEuser(user.getId());
		entity.setEusername(user.getName());
		entity.setEtime(TimeTool.getTimeDate14());
		entity.setPstate("1");
		entity = firebirdQzSchedulerDao.insertEntity(entity);
		if (entity.getAutois().equals("1")) {
			try {
				startTask(entity.getId());
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return firebirdQzSchedulerDao.insertEntity(entity);
	}

	@Override
	@Transactional
	public FirebirdQzScheduler editSchedulerEntity(FirebirdQzScheduler entity,
			LoginUser user) {
		FirebirdQzScheduler entity2 = firebirdQzSchedulerDao.getEntity(entity.getId());
		entity2.setEuser(user.getId());
		entity2.setEusername(user.getName());
		entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setAutois(entity.getAutois());
		entity2.setTaskid(entity.getTaskid());
		entity2.setTriggerid(entity.getTriggerid());
		firebirdQzSchedulerDao.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteSchedulerEntity(String entity, LoginUser user) {
		try {
			stopTask(entity);
		} catch (SchedulerException e) {
			log.error(e);
		}
		firebirdQzSchedulerDao.deleteEntity(firebirdQzSchedulerDao.getEntity(entity));
	}

	@Override
	@Transactional
	public FirebirdQzScheduler getSchedulerEntity(String id) {
		if (id == null) {
			return null;
		}
		return firebirdQzSchedulerDao.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createSchedulerSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery
				.init(query,
						"FARM_QZ_SCHEDULER A LEFT JOIN FARM_QZ_TASK B ON A.TASKID=B.ID LEFT JOIN FARM_QZ_TRIGGER C ON A.TRIGGERID=C.ID",
						"A.ID AS ID,A.AUTOIS AS AUTOIS,A.AUTOIS AS AUTOISTYPE,B.NAME AS TASKNAME,C.NAME AS CTRIGGERNAME");
		return dbQuery;
	}

	@Override
	@Transactional
	public FirebirdQzTask insertTaskEntity(FirebirdQzTask entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setCusername(user.getName());
		entity.setEuser(user.getId());
		entity.setEusername(user.getName());
		entity.setEtime(TimeTool.getTimeDate14());
		entity.setPstate("1");
		entity.setJobkey("NONE");
		try {
			for (@SuppressWarnings("rawtypes")
			Class cla : Class.forName(entity.getJobclass().trim())
					.getInterfaces()) {
				if (cla.equals(Job.class)) {
					return firebirdQzTaskDao.insertEntity(entity);
				}
			}
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("类转化异常");
		}
		throw new RuntimeException("类为实现Job接口");
	}

	@Override
	@Transactional
	public FirebirdQzTask editTaskEntity(FirebirdQzTask entity, LoginUser user) {
		FirebirdQzTask entity2 = firebirdQzTaskDao.getEntity(entity.getId());
		entity2.setEuser(user.getId());
		entity2.setEusername(user.getName());
		entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setJobclass(entity.getJobclass());
		entity2.setName(entity.getName());
		entity2.setJobkey(entity.getJobkey());
		entity2.setJobparas(entity.getJobparas());
		entity2.setJobkey("NONE");
		entity2.setPcontent(entity.getPcontent());
		try {
			for (@SuppressWarnings("rawtypes")
			Class cla : Class.forName(entity2.getJobclass().trim())
					.getInterfaces()) {
				if (cla.equals(Job.class)) {
					firebirdQzTaskDao.editEntity(entity2);
					return entity2;
				}
			}
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("类转化异常");
		}
		throw new RuntimeException("类为实现Job接口");

	}

	@Override
	@Transactional
	public void deleteTaskEntity(String entity, LoginUser user) {
		firebirdQzTaskDao.deleteEntity(firebirdQzTaskDao.getEntity(entity));
	}

	@Override
	@Transactional
	public FirebirdQzTask getTaskEntity(String id) {
		if (id == null) {
			return null;
		}
		return firebirdQzTaskDao.getEntity(id);
	}

	@Override
	public DataQuery createTaskSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query, "firebird_qz_task",
				"id,JOBCLASS,NAME,JOBKEY");
		return dbQuery;
	}

	@Override
	@Transactional
	public FirebirdQzTrigger insertTriggerEntity(FirebirdQzTrigger entity,
			LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setCusername(user.getName());
		entity.setEuser(user.getId());
		entity.setEusername(user.getName());
		entity.setEtime(TimeTool.getTimeDate14());
		entity.setPstate("1");
		return firebirdQzTriggerDao.insertEntity(entity);
	}

	@Override
	@Transactional
	public FirebirdQzTrigger editTriggerEntity(FirebirdQzTrigger entity, LoginUser user) {
		FirebirdQzTrigger entity2 = firebirdQzTriggerDao.getEntity(entity.getId());
		// entity2.setEuser(user.getId());
		// entity2.setEusername(user.getName());
		// entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setPcontent(entity.getPcontent());
		entity2.setDescript(entity.getDescript());
		entity2.setName(entity.getName());
		firebirdQzTriggerDao.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteTriggerEntity(String entity, LoginUser user) {
		firebirdQzTriggerDao.deleteEntity(firebirdQzTriggerDao.getEntity(entity));
	}

	@Override
	@Transactional
	public FirebirdQzTrigger getTriggerEntity(String id) {
		if (id == null) {
			return null;
		}
		return firebirdQzTriggerDao.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createTriggerSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query, "firebird_qz_trigger",
				"id,PCONTENT,DESCRIPT,NAME");
		return dbQuery;
	}

	@Override
	@Transactional
	public FirebirdQzTask getTaskBySchedulerId(String schedulerId) {
		return firebirdQzTaskDao.getEntity(firebirdQzSchedulerDao
				.getEntity(schedulerId).getTaskid());
	}

}
